<template>
  <div ref="boxRef" v-loading="loading">
    <page-box>
      <template #top>
        <alert-msg
          content="1.同级标签名称，不可重复2.标签名称，不可超过50个字符3.标签上限为1000个（包含停用标签）4.停用标签不影响记录中已存在标签；编辑或删除标签，会影响记录中已存在标签，请谨慎操作！"
        >
          <template #icon>
            <i class="MC_iconfont MC_icon-xinxi-mian"></i>
          </template>
        </alert-msg>
      </template>
      <template #search>
        <search-form
          ref="searchRef"
          @onSearchFun="onSearch"
          class="search"
          :fieldList="fieldList"
          :form="form"
        ></search-form>
      </template>
      <template #btn>
        <el-button @click="onSearch">查询</el-button>
      </template>
      <template #table>
        <div ref="tableRef" class="table-class">
          <tag-list
            :box="tableRef"
            ref="tagRef"
            v-if="tags.length"
            :keyWords="form.keyWords"
            :status="form.status"
            :queryKeys="queryKeys"
            :updateTagTotal="updateTagTotal"
            :total="total"
            :getList="getList"
            :value="tags"
          />
        </div>
      </template>
    </page-box>
  </div>
</template>
<script lang="ts" setup>
import pageBox from '@common/components/page-box.vue'
import alertMsg from '@common/components/alert/index.vue'
import searchForm from '@common/components/base-form/form.vue'
import { FormFiled, FormType } from '@/common/interface/form'
import { TagNode } from '@/common/interface/node'
import { onMounted, reactive, ref, toRefs, watch } from 'vue'
import http from '@/common/utils/http'
import TagList from './tag-list.vue'
import { addFields } from '@/common/utils/tree'
import { cloneDeep, debounce, isEmpty } from 'lodash'
import { EMPTY, INIT_DATA } from './constance'
import { useFilter } from './hooks/useFilter'
import mcGetCache from '@/common/utils/mc-get-cache'
interface State extends FormFiled {
  tags: TagNode[]
  initTotal: number
  loading: boolean
  queryKeys: any
}

const state: State = reactive({
  tags: [],
  queryKeys: new Set([]),
  initTotal: 0,
  fieldList: [
    {
      name: '关键字',
      field: 'keyWords',
      type: FormType.TEXT
    },
    {
      name: '状态',
      field: 'status',
      type: FormType.DROPDOWN,
      choices: [
        {
          label: '全部',
          value: EMPTY
        },
        {
          label: '启用',
          value: '1'
        },
        {
          label: '停用',
          value: '0'
        }
      ]
    }
  ],
  loading: false,
  form: { keyWords: EMPTY, status: EMPTY }
})
const { tags, form, fieldList, loading, queryKeys } = toRefs(state)
const total = ref(0)
const tagRef: any = ref(null)
const boxRef: any = ref(null)
const searchRef: any = ref(null)
const tableRef: any = ref(null)

const filterMethod = (query: any, node: any) => {
  if (query.status !== EMPTY) {
    return node.status == query.status && node.name.includes(query.keyWords)
  } else {
    return node.name.includes(query.keyWords)
  }
}

const getTags = () => state.tags

const { doFilter } = useFilter({ filterMethod }, getTags)
onMounted(async () => {
  await getList()
  await mcGetCache.$getCache('serviceLabels', 'hasObj')
})

watch(
  () => state.form.status,
  () => {
    if (state.form.status === EMPTY) {
      setTimeout(() => {
        const span = boxRef.value.querySelector('.el-select-v2__placeholder')
        span.innerText = '全部'
      })
    }
  },
  { immediate: true }
)

const getList = async () => {
  state.loading = true
  const res = await http({
    url: '/platform/action/console/service-label/list',
    method: 'POST',
    data: {}
  })
  const count = res.data.count
  const tags = !isEmpty(res.data.list) ? cloneDeep(res.data.list) : INIT_DATA
  addFields(tags)
  Object.assign(state, {
    tags,
    initTotal: count
  })
  state.loading = false
  total.value = count
  return res.data.list
}

const updateTagTotal = (isAdd?: boolean | undefined) => {
  if (isAdd === undefined) {
    total.value = state.initTotal
    return
  }
  if (isAdd) {
    total.value = total.value + 1
  } else {
    total.value = total.value - 1
  }
}

const onSearch = debounce(() => {
  setTimeout(async () => {
    state.queryKeys = doFilter(state.form)
    const list = await getList()
    addFields(list, {
      blackSizeList: [...state.queryKeys]
    })
    state.tags = list
    if (!state.form.keyWords && state.form.status === EMPTY) {
      state.queryKeys.clear()
    }
  })
}, 500)
</script>
<style lang="stylus" scoped>
.table-class {
  position: relative;
  display flex
}

.search {
  :deep(.el-input) {
    width: 180px;
  }

  :deep(.el-select-v2) {
    width: 180px;
  }
}
</style>
